package cn.elwy.rcp.ui.wizard;

import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Composite;

import cn.elwy.rcp.ui.dialog.CustomeSettings;

/**
 * 自定义向导抽象类
 * 
 * @author huangsq
 * @version 1.0, 2013-11-20
 * @since 1.0, 2013-11-20
 */
public class BaseWizard extends Wizard {

  protected String dialogId;
  protected boolean isDirty;
  protected boolean canSave = true;
  protected boolean canCancel = true;

  public BaseWizard() {
    this("BaseWizard");
  }

  public BaseWizard(String dialogId) {
    super();
    this.dialogId = dialogId;
    setNeedsProgressMonitor(true);
  }

  /**
   * 添加向导页，该向导页可支持自定义按钮事件。
   * 
   * @param page
   */
  public void addPage(BaseWizardPage page) {
    super.addPage(page);
  }

  @Override
  public void createPageControls(Composite pageContainer) {
  }

  /**
   * 不能使用直接继承于IWizardPage的向导页，需要使用继承于BaseWizardPage的向导页。 未继承BaseWizardPage的向导页，不支持自定义按钮事件。
   * 
   * @param page
   */
  @Deprecated
  public void addPage(IWizardPage page) {
    super.addPage(page);
  }

  @Override
  public IDialogSettings getDialogSettings() {
    IDialogSettings dialogSettings = super.getDialogSettings();
    if (dialogSettings != null) {
      return dialogSettings;
    }

    dialogSettings = new CustomeSettings(dialogId); //$NON-NLS-1$
    setDialogSettings(dialogSettings);
    return dialogSettings;
  }

  @Override
  public boolean performFinish() {
    if (!validatePage()) {
      return false;
    }
    getPageData();
    return true;
  }

  protected boolean validatePage() {
    IWizardPage[] pages = getPages();
    for (IWizardPage wizardPage : pages) {
      boolean pageState = ((BaseWizardPage) wizardPage).validatePage();
      if (!pageState) {
        getContainer().showPage(wizardPage);
        return false;
      }
    }
    return true;
  }

  protected void getPageData() {
    IWizardPage[] pages = getPages();
    for (IWizardPage wizardPage : pages) {
      ((BaseWizardPage) wizardPage).getPageData();
    }
  }

  public String getDialogId() {
    return dialogId;
  }

  public void setDialogId(String dialogId) {
    this.dialogId = dialogId;
  }

  public boolean isDirty() {
    return isDirty;
  }

  public void setDirty(boolean isDirty) {
    this.isDirty = isDirty;
  }

  public boolean isCanSave() {
    return canSave;
  }

  public void setCanSave(boolean canSave) {
    this.canSave = canSave;
  }

  public boolean isCanCancel() {
    return canCancel;
  }

  public void setCanCancel(boolean canCancel) {
    this.canCancel = canCancel;
  }

}